﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Log;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Log
{
    /// <summary>
    /// 日志 中介者处理类
    /// </summary>
    public class CreateLogHandler : IRequestHandler<CreateLogCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 通过构造函数注入日志仓储和automapper  两个资源
        /// </summary>
        /// <param name="logRepo"></param>
        /// <param name="mapper"></param>
        public CreateLogHandler(IBaseRepository<LogModel> logRepo,IMapper mapper)
        {
            this.logRepo = logRepo;
            this.mapper = mapper;
        }

        /// <summary>
        ///日志 中介者处理方法
        /// </summary>
        /// <param name="request">中介者添加日志要用到的参数(命令)</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateLogCommand request, CancellationToken cancellationToken)
        {
            //  request result这俩傻傻分不清楚
            ApiResult<int> result = new ApiResult<int>();

            var model = mapper.Map<LogModel>(request);
            model.Id = YitIdHelper.NextId();//雪花id
            model.CreateTime = DateTime.Now;
            var r = logRepo.Create(model);
            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "添加日志成功!";
                result.Data = r;
            }
            else {
                result.Code = ApiEnums.Fail;
                result.Msg = "添加日志失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
        }
    }
}
